import React, {memo} from 'react';
import './mobile-viewport.css'

const viewportStr = {
    one: '不设置任何跟viewport有关的meta标签时，浏览器会有一个默认的缩放值，缩小页面，使得不出现滚动条',
    two: '<meta name="viewport" content="width=1000", initial-scale=1"/>时，页面没有进行缩放，出现了横向滚动条',
    three: '<meta name="viewport" content="width=device-width", initial-scale=1"/>时，页面没有进行缩放，没有横向滚动条'
}

class MobileTest extends React.Component {
   
    constructor() {
        super()
        this.state={
            index: 'one'
        }
    }

   componentWillMount() {
        this.change('one')
      
   }
   
    change = (e) => {
        
        const index  = e.target && e.target.dataset.index || e;
        let str = "";
        switch (index) {
            case 'one':
                str = ""
                break;
            case 'two':
                str = 'width=1000, initial-scale=1'
                break;
            case 'three':
                str = 'width=device-width", initial-scale=1'
                break;
        }
        let metaEl = document.querySelector('meta[name="viewport"]');
        metaEl.setAttribute('content', str);
        this.setState({index})
    }
    
    componentWillUnmount() {
        this.change('three');
    }

    

    render() {
        const { change } = this;
        const { index } = this.state;
        return (
            <div id="mobile-viewport">
                <h2>viewport</h2>
                <div onClick={change}>
                    {
                        index==="one" ? (
                            <button data-index="one" className={index==="one"?"active":""}>不设置meta标签</button>
                        ) : null
                    }
                    
                    <button data-index="two" className={index==="two"?"active":""}>width设置为1000</button>
                    <button data-index="three" className={index==="three"?"active":""}>width设置为device-width</button>
                </div>
                
                {/* <button onClick={()=>alert(document.documentElement.clientWidth)}>layout viewport宽度</button>
                <button onClick={()=>alert(window.innerWidth)}>visual viewport宽度</button> */}
                <br />
                <div>
                    {index !="one" ? "当设置了" : ""} <br />
                    {viewportStr[index]}            
                </div>
                <br/>
            </div>
        )
    }
}

export default memo(MobileTest);